import React, {useState, useEffect, useRef, forwardRef, useImperativeHandle} from 'react';
import {
    Platform,
    StyleSheet, Text,
    TouchableOpacity,View
} from 'react-native';
import * as S from "../Category/styles";
import {useCalculate} from "../../hooks/useCalculate";
import {useStatistics} from "../../hooks/useStatistics";
import {getTodayAndSixDaysAgoDate} from "../../utils/utils";

const dateType = [
    {'key':'DAY','title':'日'},
    {'key':'WEEK','title':'周'},
    {'key':'MONTH','title':'月'},
    {'key':'YEAR','title':'年'},
]

const LevelView = forwardRef((props,ref) => {

    const [ selectLevelIndex, setSelectLevelIndex ] = useState(1);
    const [ selectDateType, setSelectDateType ] = useState(dateType[0].key);
    const [ timeSlotIndex, setTimeSlotIndex ] = useState(0);
    const [ startDate, setStartDate ] = useState('');
    const [ endDate, setEndDate ] = useState('');
    const [ todayDate, setTodayDate ] = useState('');
    const [ dateTimeWithoutYear, setDateTimeWithoutYear ] = useState([]);
    const { loadCalculate, timeSlot, loadCalculateChildren, loadTimeSlot } = useCalculate();
    const { loadStatistics, loadStatisticsEvents, statistics,loadStatisticsTimeSlot, statisticsTimeSlot } = useStatistics();
    const scrollRef = useRef(null);
    const lock = useRef(false);

    useEffect(()=>{
        if (!lock.current) {
            lock.current = true;
            let today = getTodayAndSixDaysAgoDate().dateTime[1];
            setTodayDate(today);
            setDateTimeWithoutYear([getTodayAndSixDaysAgoDate().dateTimeWithOutYear[0].split('-').join('.'),getTodayAndSixDaysAgoDate().dateTimeWithOutYear[1].split('-').join('.'),]);
            getTimeSlot(today,dateType[0].key);
        }

        let timeSlotData = props?.from == 'calculate' ? timeSlot : statisticsTimeSlot;
        if (timeSlotData && timeSlotData.length > 0) {
            setStartDate(timeSlotData[timeSlotData.length-1].startDate);
            setEndDate(timeSlotData[timeSlotData.length-1].endDate);
            if (scrollRef) {
                setTimeSlotIndex(timeSlotData.length-1);
                scrollRef?.current?.scrollToEnd();
            }
            props.titleCallback && props.titleCallback(timeSlotData[timeSlotData.length-1].titleName);
            loadData(selectLevelIndex, selectDateType, timeSlotData[timeSlotData.length-1].startDate, timeSlotData[timeSlotData.length-1].endDate);
        }
    },props?.from == 'calculate'? [timeSlot]:[statisticsTimeSlot])

    useImperativeHandle(ref,()=>({
        refresh: () => {
            loadData(selectLevelIndex, selectDateType, startDate, endDate);
        },
        loadCalculateData: (startDateParam,endDateParam) => {
            loadData(selectLevelIndex,'',startDateParam, endDateParam);
        },
        loadParentData: (parentId,level) => {
            loadStatisticsData(parentId, level, startDate, endDate);
        },
        loadChartData: (parentId,level) => {
            loadChartEventData(parentId, level, startDate, endDate);
        },
        loadSetDateTimeWithoutYear: (data) => {
            setDateTimeWithoutYear(data);
        },
        reLoadTimeSlot: (data) => {
            getTimeSlot(data,selectDateType);
        },
    }))

    const loadChartEventData = (parentId: any, level: any, startDate: string, endDate: string) => {

        let eventsData = [];
        statistics?.map((item) => {
            eventsData.push({
                id: item?.id,
                level: item?.level,
            })
        })
        let params = {
            events: eventsData,
            type: selectDateType,
            startDate: startDate,
            endDate: endDate,
        }
        loadStatisticsEvents(params).then(function (response) {
        });
    }

    const setLevelIndex = (index) => {
        setSelectLevelIndex(index);
        props.levelCallback && props.levelCallback(index);
        props.periodCallback && props.periodCallback(false);
        loadData(index, selectDateType, startDate, endDate);
    }

    const getTimeSlot = (day,type) => {

        if (props?.from == 'calculate') {
            loadTimeSlot({
                day: day,
                type: type,
            }).then(function (response) {
            });
        } else {
            loadStatisticsTimeSlot({
                day: day,
                type: type,
            }).then(function (response) {
            });
        }
    }

    const setDateType = (type) => {
        getTimeSlot(todayDate,type);
        props.periodCallback && props.periodCallback(false);
        props.clearEventNameCallback && props.clearEventNameCallback();
        setSelectDateType(type);
    }

    const clickTimeSlot = (item, index) => {
        console.log('-clickTimeSlot-',item)
        props.titleCallback && props.titleCallback(item?.titleName);
        setTimeSlotIndex(index);
        setStartDate(item?.startDate);
        setEndDate(item?.endDate);
        props.periodCallback && props.periodCallback(false);
        props.clearEventNameCallback && props.clearEventNameCallback();
        loadData(selectLevelIndex, selectDateType, item?.startDate, item?.endDate);
    }

    const loadStatisticsData = (parentId,level,startDateParam,endDateParam) => {
        loadStatistics({
            parentId: parentId,
            level: level,
            startDate: startDateParam,
            endDate: endDateParam,
        }).then(function (response) {
            props?.setLoading&&props.setLoading(false);
            props?.loadCallback&&props.loadCallback();
        });
    }

    const loadData = (levelIndex, dateType, startDateParam, endDateParam) => {
        props?.setLoading&&props.setLoading(true);
        props.dateCallback && props.dateCallback([startDateParam,endDateParam]);
        console.log('---loadData--',levelIndex, dateType, startDateParam, endDateParam)
        if (props?.from == 'staticstics') {
            //分析
            loadStatisticsData('',1,startDateParam,endDateParam);
        } else {
            //核算
            if (levelIndex === 1) {
                loadCalculate({
                    startDate: startDateParam,
                    endDate: endDateParam,
                }).then(function (response) {
                    props?.setLoading&&props.setLoading(false);
                    props?.loadCallback&&props.loadCallback();
                });
            } else {
                loadCalculateChildren({
                    level: levelIndex,
                    startDate: startDateParam,
                    endDate: endDateParam,
                }).then(function (response) {
                    props?.setLoading&&props.setLoading(false);
                    props?.loadCallback&&props.loadCallback();
                });
            }
        }
    }

    const clickPeriodDate = () => {
        setSelectDateType('');
        props?.clickPeriodDate&&props.clickPeriodDate();
    }

    // console.log('-====level==state==',timeSlot,'timeSlotIndex:',timeSlotIndex,'startDate:',startDate,'endDate:',endDate)

    return (
        <View style = {styles.levelOne}>
            {
                props?.from == 'calculate'?
                    <View style = {styles.levelOneTop}>
                        <TouchableOpacity
                            style={[styles.levelOneButton,{backgroundColor: selectLevelIndex === 1 ? '#fff' : 'rgba(232, 232, 232, 1)'}]}
                            onPress={() => setLevelIndex(1)}
                        >
                            <Text style={[styles.topLevelText,{fontWeight: selectLevelIndex === 1 ? 'bold' : 'normal'}]}>一级</Text>
                        </TouchableOpacity>
                        <TouchableOpacity
                            style={[styles.levelOneButton,{backgroundColor: selectLevelIndex === 2 ? '#fff' : 'rgba(232, 232, 232, 1)'}]}
                            onPress={() => setLevelIndex(2)}
                        >
                            <Text style={[styles.topLevelText,{fontWeight: selectLevelIndex === 2 ? 'bold' : 'normal'}]}>二级</Text>
                        </TouchableOpacity>
                        <TouchableOpacity
                            style={[styles.levelOneButton,{backgroundColor: selectLevelIndex === 3 ? '#fff' : 'rgba(232, 232, 232, 1)'}]}
                            onPress={() => setLevelIndex(3)}
                        >
                            <Text style={[styles.topLevelText,{fontWeight: selectLevelIndex === 3 ? 'bold' : 'normal'}]}>三级</Text>
                        </TouchableOpacity>
                    </View>:null
            }
            <View style = {[styles.levelOneMid,{marginBottom: selectDateType ? 0 : 16}]}>
                <View style={styles.levelOneDateView}>
                    {
                        dateType.map((item)=>{
                            return (
                                <TouchableOpacity
                                    key={'date_'+item.key}
                                    style={[styles.levelOneDateButton,{backgroundColor: selectDateType === item.key ? '#fff' : 'rgba(232, 232, 232, 1)'}]}
                                    onPress={() => setDateType(item.key)}
                                >
                                    <Text style={[styles.topLevelText,{fontWeight: selectDateType === item.key ? 'bold' : 'normal'}]}>{item.title}</Text>
                                </TouchableOpacity>
                            )
                        })
                    }
                </View>
                <TouchableOpacity
                    style={[styles.levelDateTimeButton,{backgroundColor: props.selectPeriod?'#fff':'rgba(232, 232, 232, 1)'}]}
                    onPress={clickPeriodDate}>
                    {
                        dateTimeWithoutYear?.length > 0 ? <Text style={styles.topLevelText}>{dateTimeWithoutYear.join('-')}</Text> : null
                    }
                </TouchableOpacity>
            </View>

            {
                selectDateType ?
                    <S.Container4
                        ref={scrollRef}
                        horizontal
                        showsHorizontalScrollIndicator={false}
                    >
                        <S.Buttons2Wrapper>
                            {(props?.from == 'calculate' ? timeSlot : statisticsTimeSlot).map((item,index) => {
                                return (
                                    <TouchableOpacity
                                        key={'timeSlot_'+index}
                                        style={styles.levelTimeButton}
                                        onPress={() => clickTimeSlot(item,index)}
                                    >
                                        <Text style={[{fontFamily: 'HarmonyOS_Sans_SC_Bold',color: timeSlotIndex === index ? 'rgba(48, 118, 217, 1)' : 'rgba(142, 142, 147, 1)',fontSize: 14}]}>
                                            {item?.name}
                                        </Text>
                                    </TouchableOpacity>
                                );
                            })}
                        </S.Buttons2Wrapper>
                    </S.Container4>:null
            }
        </View>
    )
});

export default LevelView;

const styles = StyleSheet.create({
    levelOne: {
        marginHorizontal: 18,
    },
    levelOneTop: {
        backgroundColor: 'rgba(232, 232, 232, 1)',
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 8,
        marginBottom: 12,
        height: 36,
        borderRadius: 12,
        paddingHorizontal: 2,
        justifyContent: 'space-between',
    },
    levelOneButton: {
        width: '30%',
        height: 32,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 10,
    },
    topLevelText: {
        color: 'rgba(44, 44, 46, 1)',
        fontSize: 14,
        fontFamily: 'HarmonyOS_Sans_SC_Bold'
    },
    levelOneMid: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
    },
    levelOneDateView: {
        backgroundColor: 'rgba(232, 232, 232, 1)',
        flexDirection: 'row',
        alignItems: 'center',
        height: 36,
        borderRadius: 12,
        paddingHorizontal: 2,
        width: '64%',
    },
    levelOneDateButton: {
        width: '25%',
        height: 32,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 10,
    },
    levelDateTimeButton: {
        width: '32%',
        backgroundColor: 'rgba(232, 232, 232, 1)',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        height: 36,
        borderRadius: 12,
    },
    levelOneBottom: {

    },
    levelTimeButton: {
        height: 28,
        alignItems: 'center',
        justifyContent: 'center',
        marginRight: 20,
    }
});
